#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include "Comm.hpp"

const static char *path = "/";
const static char *dev_null = "/dev/null";

using namespace Me;

class Daemon
{
public:
    Daemon(int ischdir = 0, int isclose = 0) // ischild表示是否改变当前路径为/，isclose表示是否关闭标准输入、标准输出和标准错误
    {
        pid_t pid = fork();
        if (pid < 0)
        {
            std::cerr << "fork error, errno " << errno << "is " << strerror(errno);
            exit(EXIT_FALURE_ME);
        }
        else if (pid > 0)
        {
            exit(EXIT_SUCCESS_ME);
        }
        pid_t newsid = setsid();
        if (newsid < 0)
        {
            std::cerr << "set a new session error, errno " << errno << "is " << strerror(errno) << std::endl;
            exit(EXIT_FAILURE);
        }
        else
        {
            std::cout << "set a new session success, new sid is " << newsid << std::endl;
            if (ischdir)
                chdir(path);
            if (isclose)
            {
                close(0);
                close(1);
                close(2);
            }
            else
            {
                int fd = open(dev_null, O_RDONLY | O_WRONLY);
                dup2(fd, 0);
                dup2(fd, 1);
                dup2(fd, 2);
                close(fd);
            }
        }
    }
};